<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card>
      <el-alert
        title="注意： 只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <div>
        <p>
          选择商品分类：
          <el-cascader
            v-model="selectedKeys"
            :options="casList"
            :props="propsparams"
            @change="handleChange"
          ></el-cascader>
        </p>
      </div>
      <!-- 添加动态静态参数弹框 -->
      <el-dialog
        title="添加动态参数"
        :visible.sync="addmanyVisible"
        width="50%"
      >
        <el-form
          :model="addmanyForm"
          :rules="addmanycaterules"
          ref="addmanycateref"
          label-width="100px"
          class="demo-ruleForm"
          @close="addmanyClosed"
        >
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="addmanyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addmanyVisible = false">取 消</el-button>
          <el-button type="primary" @click="addmanyFormV">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="添加属性参数"
        :visible.sync="addonlyVisible"
        width="50%"
      >
        <el-form
          :model="addonlyForm"
          :rules="addonlycaterules"
          ref="addonlytcateref"
          label-width="100px"
          class="demo-ruleForm"
          @close="addmanyClosed"
        >
          <el-form-item label="属性名称" prop="attr_name">
            <el-input v-model="addonlyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addonlyVisible = false">取 消</el-button>
          <el-button type="primary" @click="addonlyFormV">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改动态静态参数弹框 -->
      <el-dialog
        title="修改动态参数"
        :visible.sync="EditmanyVisible"
        width="50%"
      >
        <el-form
          :model="EditmanyForm"
          :rules="addmanycaterules"
          ref="Editmanycateref"
          label-width="100px"
          class="demo-ruleForm"
          @close="addmanyClosed"
        >
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="EditmanyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="EditmanyVisible = false">取 消</el-button>
          <el-button type="primary" @click="EditmanyFormV">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改属性参数"
        :visible.sync="EditmanyVisible"
        width="50%"
      >
        <el-form
          :model="EditmanyForm"
          :rules="addmanycaterules"
          ref="Editmanycateref"
          label-width="100px"
          class="demo-ruleForm"
          @close="addmanyClosed"
        >
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="EditmanyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="EditmanyVisible = false">取 消</el-button>
          <el-button type="primary" @click="EditmanyFormV">确 定</el-button>
        </span>
      </el-dialog>
      <template>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtndisabled"
              @click="addmanyVisible = true"
              >添加参数</el-button
            >
            <el-table :data="manyTableData" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                    <!-- 不论你是失去焦点还是按回车键都是添加 -->
                    <!-- 这是回车 -->
                    <!-- @keyup.enter.native="handleInputConfirm" -->
                    <!-- 这是失去焦点 -->
                    <!-- @blur="handleInputConfirm" -->
                  </el-input>
                  <!-- 添加按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"> </el-table-column>
              <el-table-column label="参数名称" prop="attr_name">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="Editmany(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delkete"
                    @click="deleteonly(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态配置" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtndisabled"
              @click="addonlyVisible = true"
              >添加属性</el-button
            >
            <el-table :data="onlyTableData" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(i, scope.row)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"> </el-table-column>
              <el-table-column label="属性名称" prop="attr_name">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="Editmany(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteonly(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeName: 'many',
      casList: [],
      selectedKeys: [],
      propsparams: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      paramsdata: [
        {
          label: '参数名称',
          prop: 'cat_name'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      manyTableData: [],
      onlyTableData: [],
      // 添加参数
      // 添加动态参数
      addmanyVisible: false,
      // 添加静态属性
      addonlyVisible: false,
      // 添加动态参数表单规则
      addmanycaterules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      addonlycaterules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 添加动态参数
      addmanyForm: {
        attr_name: ''
      },
      addonlyForm: {
        attr_name: ''
      },
      // 修改参数
      EditonlyForm: {},
      EditmanyForm: {},
      EditmanyVisible: false,
      EditonlyVisible: false
    }
  },
  created() {
    this.getcasList()
  },
  methods: {
    handleClick() {
      this.getParamsDate()
      // console.log(this.activeName)
    },
    async getcasList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      // console.log(res.data)
      this.casList = res.data
    },
    handleChange() {
      this.getParamsDate()
      // console.log(this.activeName)
    },
    async getParamsDate() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // console.log(this.opens)
      const { data: res } = await this.$http.get(
        `categories/${this.opens}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // 字符串转成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addmanyFormV() {
      this.$refs.addmanycateref.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.opens}/attributes`,
          {
            attr_name: this.addmanyForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: 'a,b,c'
          }
        )
        // console.log(res.data)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功 ')
        this.getParamsDate()
        this.addmanyVisible = false
      })
    },
    addmanyClosed() {
      this.$refs.Editmanycateref.resetFields()
    },
    addonlyFormV() {
      this.$refs.addonlytcateref.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.opens}/attributes`,
          {
            attr_name: this.addonlyForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: 'a,b,c'
          }
        )
        // console.log(res.data)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功 ')
        this.getParamsDate()
        this.addonlyVisible = false
      })
    },
    // 删除按钮
    async deleteonly(code) {
      // console.log(code)
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      ).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.error('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.opens}/attributes/` + code,
        {
          attr_sel: this.activeName
        }
      )
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsDate()
    },
    async Editmany(id) {
      console.log(id)
      const { data: res } = await this.$http.get(
        `categories/${this.opens}/attributes/` + id,
        {
          attr_sel: this.activeName
        }
      )
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.EditmanyForm = res.data
      this.EditmanyVisible = true
    },
    EditmanyFormV() {
      this.$refs.Editmanycateref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.opens}/attributes/` + this.EditmanyForm.attr_id,
          {
            attr_name: this.EditmanyForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新参数失败')
        }
        this.$message.success('更新成功')
        this.getParamsDate()
        this.EditmanyVisible = false
      })
    },
    handleClose(index, row) {
      // 删除对应索引的参数可选项
      row.attr_vals.splice(index, 1)
      // 调用函数，完成保存可选项的操作
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      // 封装函数，完成保存可选项的操作
      // 发起请求，保存参数细项
      const { data: res } = await this.$http.put(
        `categories/${this.opens}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }

      this.$message.success('修改参数项成功')
    },
    showInput(row) {
      row.inputVisible = true
      // 自动能够获取焦点
      // $nextTick 当页面被渲染之后才会调用回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去焦点或者按下enter键
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      const inputValue = row.inputValue
      if (inputValue) {
        row.attr_vals.push(row.inputValue.trim())
      }
      row.inputVisible = false
      row.inputValue = ''
      // 发起请求调用接口
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtndisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    opens() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    }
  }
}
</script>

<style>
.el-tag {
  margin: 0px 10px;
}
.input-new-tag {
  width: 100px !important;
}
</style>
